import pool from '../config/database'
import { RowDataPacket, ResultSetHeader } from 'mysql2'

export interface AIModel extends RowDataPacket {
  id: number
  user_id: number
  name: string
  model: string
  api_key: string
  base_url: string
  is_default: boolean
  status: number
}

export class AIModelModel {
  // 获取用户的所有模型
  static async findByUserId(userId: number): Promise<AIModel[]> {
    const [rows] = await pool.execute<AIModel[]>(
      'SELECT * FROM ai_models WHERE user_id = ? AND status = 1',
      [userId]
    )
    return rows
  }

  // 获取单个模型
  static async findById(id: number, userId: number): Promise<AIModel | null> {
    const [rows] = await pool.execute<AIModel[]>(
      'SELECT * FROM ai_models WHERE id = ? AND user_id = ? AND status = 1',
      [id, userId]
    )
    return rows[0] || null
  }

  // 创建模型
  static async create(data: {
    user_id: number
    name: string
    model: string
    api_key: string
    base_url: string
    is_default: boolean
  }) {
    // 如果设置为默认，先将其他模型设置为非默认
    if (data.is_default) {
      await pool.execute(
        'UPDATE ai_models SET is_default = FALSE WHERE user_id = ?',
        [data.user_id]
      )
    }

    const [result] = await pool.execute<ResultSetHeader>(
      'INSERT INTO ai_models (user_id, name, model, api_key, base_url, is_default) VALUES (?, ?, ?, ?, ?, ?)',
      [data.user_id, data.name, data.model, data.api_key, data.base_url, data.is_default]
    )
    return result.insertId
  }

  // 更新模型
  static async update(id: number, userId: number, data: {
    name?: string
    model?: string
    api_key?: string
    base_url?: string
    is_default?: boolean
  }) {
    // 如果设置为默认，先将其他模型设置为非默认
    if (data.is_default) {
      await pool.execute(
        'UPDATE ai_models SET is_default = FALSE WHERE user_id = ? AND id != ?',
        [userId, id]
      )
    }

    const [result] = await pool.execute<ResultSetHeader>(
      'UPDATE ai_models SET ? WHERE id = ? AND user_id = ?',
      [data, id, userId]
    )
    return result.affectedRows > 0
  }

  // 删除模型
  static async delete(id: number, userId: number) {
    const [result] = await pool.execute<ResultSetHeader>(
      'UPDATE ai_models SET status = 0 WHERE id = ? AND user_id = ? AND is_default = FALSE',
      [id, userId]
    )
    return result.affectedRows > 0
  }

  // 设置默认模型
  static async setDefault(id: number, userId: number) {
    await pool.execute(
      'UPDATE ai_models SET is_default = FALSE WHERE user_id = ?',
      [userId]
    )
    const [result] = await pool.execute<ResultSetHeader>(
      'UPDATE ai_models SET is_default = TRUE WHERE id = ? AND user_id = ?',
      [id, userId]
    )
    return result.affectedRows > 0
  }
} 